package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.bean.PageConfig;
import com.example.demo.bean.PageConfigItem;
import com.example.demo.service.PageConfigItemService;
import com.example.demo.service.PageConfigService;
import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequiredArgsConstructor
@RequestMapping("/preview")
public class PageViewController {

    private final PageConfigService configService;
    private final PageConfigItemService itemService;

    /**
     * 新窗口预览：把 config + items 拼成 JSON，注入 index.html 的 window.CONFIG
     */
    @GetMapping("/{id}")
    public String preview(@PathVariable Integer id, Model model) throws IOException {
        System.out.println("预览配置ID: " + id);
        PageConfig config = configService.getById(id);
        if (config == null) throw new RuntimeException("配置不存在");

        QueryWrapper<PageConfigItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("page_config_id", id);
        queryWrapper.orderByAsc("order_index"); // 按照 order_index 排序
        List<PageConfigItem> items = itemService.list(queryWrapper);

        // 1. 组装hero部分
        JSONObject root = new JSONObject();
        JSONObject hero = new JSONObject();
        hero.put("bg", config.getBackgroundUrl());
        hero.put("title", config.getTitle());
        hero.put("subtitle", config.getSubTitle());
        hero.put("speakerContent", config.getSpeakerContent());
        hero.put("id", config.getId());
        root.put("hero", hero);

        // 2. 按照保存顺序处理 modules
        JSONArray modules = new JSONArray();

        for (PageConfigItem item : items) {
            JSONObject module = new JSONObject();

            switch (item.getContentType()) {
                case MIXED:
                    // 图文类型：直接解析 content 字段
                    module.put("type", "mixed");
                    try {
                        if (item.getContent() != null && !item.getContent().isEmpty()) {
                            JSONArray mixedList = JSON.parseArray(item.getContent());
                            module.put("list", mixedList);
                        } else {
                            module.put("list", new JSONArray());
                        }
                    } catch (Exception e) {
                        System.err.println("解析图文内容失败: " + item.getContent());
                        e.printStackTrace();
                        module.put("list", new JSONArray());
                    }
                    break;

                case IMAGE:
                    // 图片类型：使用 list 字段
                    module.put("type", "image");
                    if (item.getList() != null && !item.getList().isEmpty()) {

                        List<String> urlList = Arrays.stream(item.getList().split(","))
                                .map(String::trim)
                                .filter(s -> !s.isEmpty())
                                .collect(Collectors.toList());
                        JSONArray imageList = new JSONArray();
                        imageList.addAll(urlList);
                        module.put("list", imageList);
                    } else {
                        System.out.println("tu 222");
                        module.put("list", new JSONArray());
                    }
                    break;

                case VIDEO:
                    // 视频类型：使用 list 字段
                    module.put("type", "video");
                    if (item.getList() != null && !item.getList().isEmpty()) {
                        System.out.println("video 111");
                        List<String> urlList = Arrays.stream(item.getList().split(","))
                                .map(String::trim)
                                .filter(s -> !s.isEmpty())
                                .collect(Collectors.toList());
                        JSONArray videoList = new JSONArray();
                        videoList.addAll(urlList);
                        module.put("list", videoList);
                    } else {
                        System.out.println("video 222");
                        module.put("list", new JSONArray());
                    }
                    break;

                case TEXT:
                    module.put("type", "text");
                    module.put("text", item.getContent() != null ? item.getContent() : "");
                    break;
            }

            modules.add(module);
        }

        root.put("modules", modules);
        System.out.println("生成的预览配置: " + JSON.toJSONString(root, true));

        model.addAttribute("configJson", root.toJSONString());
        return "index2";
    }

}
